/**
 * Created by Gibbs on 2021/1/31.
 * Copyright (c) 2021 Gibbs. All rights reserved.
 */

#include "CommonUtilJni.h"
#include "JniHelper.h"

jclass CommonUtilJni::playerClass = nullptr;
jmethodID CommonUtilJni::findDecoderForFormatMethod = nullptr;
jmethodID CommonUtilJni::getMediaCodecSampleFmtMethod = nullptr;

void CommonUtilJni::init() {
    JNIEnv *env = JniHelper::getJNIEnv();
    playerClass = env->FindClass("com/gibbs/gplayer/CommonUtil");
    playerClass = (jclass) (env->NewGlobalRef(playerClass));
    findDecoderForFormatMethod =
            env->GetStaticMethodID(playerClass, "findDecoderForFormat", "(Ljava/lang/String;)Ljava/lang/String;");
    getMediaCodecSampleFmtMethod =
            env->GetStaticMethodID(playerClass, "getMediaCodecSampleFmt", "(I)I");
}

std::string CommonUtilJni::findDecoderForFormat(const char *format) {
    bool attach = JniHelper::attachCurrentThread();

    JNIEnv *env = JniHelper::getJNIEnv();
    jstring jFormat = format ? JniHelper::newStringUTF(env, format) : nullptr;

    jobject jobj = JniHelper::callStaticObjectMethod(playerClass, findDecoderForFormatMethod, jFormat);
    if (jFormat) {
        env->DeleteLocalRef(jFormat);
    }

    std::string codecName = JniHelper::getStringUTF(env, (jstring) (jobj));

    if (attach) {
        JniHelper::detachCurrentThread();
    }

    return codecName;
}

int CommonUtilJni::getMediaCodecSampleFmt(int fmt) {
    bool attach = JniHelper::attachCurrentThread();

    int result = JniHelper::callStaticIntMethod(playerClass, getMediaCodecSampleFmtMethod, fmt);

    if (attach) {
        JniHelper::detachCurrentThread();
    }

    return result;
}
